<template>
  <div class="upload-model-box flex f-j-c overflow-scroll">
    <div>
      <modelUpload
        ref="modelUpload"
        v-show="stepActive == 0"
        :kindSelectItem="kindSelectItem"
        :versionInfo="versionList[versionActive]"
      ></modelUpload>
      <imgUpload
        ref="imgUploadRef"
        v-show="stepActive != 0"
        :setActiveImg="setActiveImg"
        @imgChange="imgChange"
        @setImgUpload="setImgUpload"
        :backImgData="backImgData"
        :versionInfo="versionList[versionActive]"
      ></imgUpload>
    </div>

    <!-- 右侧信息 -->
    <div class="model-info-content-box">
      <div class="user-info-box f-j-sb-a-c">
        <div class="user-info f-a-c">
          <userAvatar
            :userImgs="userInfo.avatar"
            :showDv="userInfo.staus == 1"
          ></userAvatar>

          <div class="user-name-box">
            <div class="user-name">{{ userInfo.name || "userName" }}</div>
            <div class="user-num f-a-c">
              <div class="f-a-c">
                <img src="@/assets/image/icon-download@2x.png" alt="" />
                <span>{{ numToKW(userInfo.downNum || 0) }}</span>
              </div>
              <div class="f-a-c">
                <img src="@/assets/image/icon-xhs@2x.png" alt="" />
                <span>{{ numToKW(userInfo.likeNum || 0) }}</span>
              </div>
            </div>
          </div>
        </div>
        <!-- <div class="btn f-j-a-c" v-if="stepActive == 2" @click="pushModel">发布</div> -->
      </div>

      <!-- 步骤 -->
      <div class="model-info-step f-j-sb-a-c">
        <div
          class="step-item f-a-c"
          :class="{ 'step-item-active': index <= stepActive }"
          v-for="(item, index) in stepList"
          :key="index"
        >
          <div class="step f-a-c">
            <div class="step-circle f-j-a-c">
              {{ item.num }}
            </div>
            <div class="step-title">{{ item.title }}</div>
          </div>
          <div
            class="setp-line"
            :class="{ 'step-line-active': index < stepActive }"
            v-if="index != stepList.length - 1"
          ></div>
        </div>
      </div>
      <!-- 版本 -->
      <div class="model-version f-a-c">
        <div
          class="model-version-item f-j-a-c"
          :class="{ 'model-version-item-active': index == versionActive }"
          v-for="(item, index) in versionList"
          :key="index"
          @click="versionClick(item, index)"
        >
          版本{{ item.modelVersion + 1 }}
        </div>

        <div
          class="model-version-item model-version-item-active f-j-a-c"
          @click="addVersion"
          v-if="
            versionList.length < 4 &&
            modelId &&
            showAddVersion &&
            isExamine != 3
          "
        >
          <svg-icon name="icon-tianjia-blue" class="add-icon"></svg-icon>
          <span>添加版本</span>
        </div>
      </div>

      <modelInfo
        ref="uploadModelInfo"
        @kindChange="kindChange"
        v-show="stepActive == 0"
        :versionInfo="versionList[versionActive]"
      ></modelInfo>
      <imgInfo
        ref="uploadImgInfo"
        @setActiveImgText="setActiveImgText"
        :activeImg="activeImg"
        :modelInfo="modelPutData[0] ? modelPutData[0] : {}"
        v-show="stepActive != 0"
        :versionInfo="versionList[versionActive]"
      ></imgInfo>

      <div class="f-a-c">
        <el-checkbox
          class="agreement-checkbox"
          v-model="agreement"
          label="我已阅读并同意"
          size="large"
        />
        <a
          class="agreement-link"
          href="http://i-desai.com/User_protocol.pdf"
          target="_blank"
          >《用户协议》</a
        >
      </div>

      <div class="f-a-c">
        <div
          class="btn next-btn f-j-a-c"
          @click="lastClick"
          v-if="stepActive > 0"
        >
          上一步
        </div>
        <div
          class="btn next-btn f-j-a-c"
          @click="nextClick"
          v-if="stepActive < 2"
        >
          下一步
        </div>

        <div
          class="btn next-btn f-j-a-c"
          @click="updateModel"
          v-if="versionList[versionActive].id && stepActive == 2"
        >
          确认修改
        </div>

        <div
          class="btn next-btn f-j-a-c"
          @click="pushModel"
          v-else-if="stepActive == 2"
        >
          发布
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import {
  defineComponent,
  reactive,
  toRefs,
  onUnmounted,
  onMounted,
  computed,
  getCurrentInstance,
  ref,
} from "vue";
import upload from "@/components/upload.vue";
// import modelUpload from "./components/modelUpload.vue";
// import modelInfo from "./components/modelInfo.vue";
// import imgUpload from "./components/imgUpload.vue";
// import imgInfo from "./components/imgInfo.vue";
import userAvatar from "@/components/userAvatar.vue";
import { numToKW } from "@/utils/common.js";
import {
  putFile,
  addpicture,
  modelDetailsExamine,
  modelOther,
  modelUpdate,
  modelAddVersion,
  imgUpdate,
} from "@/axios/api.js";
import { ElMessage } from "element-plus";
export default defineComponent({
  components: {
    upload,
    // modelUpload,
    // modelInfo,
    // imgUpload,
    // imgInfo,
    userAvatar,
  },
  setup(props, { attrs, slots, emit }) {
    const router = useRouter();
    const { proxy } = getCurrentInstance();
    const store = useStore();

    let uploadModelInfo = ref(null); //模型信息
    let modelUpload = ref(null); //模型上传
    let imgUploadRef = ref(null); //图片上传
    let uploadImgInfo = ref(null); //图片信息

    let data = reactive({
      stepList: [
        {
          num: "01",
          title: "编辑模型",
        },
        {
          num: "02",
          title: "编辑图片",
        },
        {
          num: "03",
          title: "发布模型",
        },
      ],
      stepActive: 0, //步骤
      versionList: [
        {
          modelVersion: 0,
        },
      ],
      versionActive: 0, //版本选择下标
      // showVaeUplod: false, //显示vae
      kindSelectItem: "", //种类选中
      activeImg: "", //当前轮播图片
      setActiveImg: "", //修改当前轮播图片
      agreement: false, //同意用户协议
      modelBackData: "", //模型文件回传
      backImgData: [], //图片文件回传
      modelPutData: [], //上传参数
      modelId: "", //当前修改的模型id
      showAddVersion: true, //添加版本显示按钮
      isExamine: 0, //审核状态
    });

    let userInfo = computed(() => {
      return store.state.minUserInfo;
    });

    let uploadSucess = (result) => {
      console.log(result);
    };

    // 种类选择切换
    let kindChange = (item) => {
      data.kindSelectItem = item;
      // data.showVaeUplod = showVae;
    };

    // 图片change
    let imgChange = (img) => {
      // console.log(img);
      data.activeImg = img;
    };

    // 图片修改回传
    let setImgUpload = (img) => {
      // console.log(img)
      data.backImgData = img;
    };

    // 图片信息修改图片upload的提示词
    let setActiveImgText = (img) => {
      data.setActiveImg = img;
    };

    // 获取模型详情
    let getDetail = (id) => {
      modelDetailsExamine({
        id,
      }).then((res) => {
        let resultData = res.data;
        data.versionActive = resultData.findIndex((item) => item.id == id);
        data.versionList = resultData.sort((a, b) => {
          return a.modelVersion - b.modelVersion;
        });
        getModelOther(id);
      });
    };

    // 获取模型更多信息
    let getModelOther = (id) => {
      modelOther({
        id,
      }).then((res) => {
        let resultData = res.data;
        store.commit("setUpdateModelInfo", resultData);
      });
    };

    // 添加版本
    let addVersion = () => {
      let maxVersion = 0;
      data.versionList.forEach((item) => {
        if (item.modelVersion > maxVersion) maxVersion = item.modelVersion;
      });
      let obj = {
        modelVersion: maxVersion + 1,
      };
      data.versionList.push(obj);
      data.showAddVersion = false;
    };

    // 版本切换点击
    let versionClick = (item, index) => {
      data.versionActive = index;
      data.stepActive = 0;
      if (data.versionList[index].id) {
        getModelOther(data.versionList[index].id);
        // console.log("切换模型");
      } else {
        data.kindSelectItem = "";
        // store.commit("delUpdateModelInfo");
      }
    };

    // 上一步
    let lastClick = () => {
      data.stepActive = data.stepActive - 1;
      // if (data.stepActive == 0) {
      //   proxy.$nextTick(() => {
      //     let modelItem = data.modelPutData[0];
      //     data.modelBackData = {
      //       modelList: modelItem.data,
      //       vae: modelItem.vaeFile,
      //     };
      //     if (modelItem.checkPoint === 0) {
      //       data.showVaeUplod = true;
      //     }
      //   });
      // }
    };
    let replaceGreaterSymbol = (text, replacement) => {
      var regex = />/;
      if (regex.test(text)) {
        return text.replace(regex, replacement);
      } else {
        return text;
      }
    };
    // 下一步
    let nextClick = () => {
      if (data.stepActive == 0) {
        let infoData = uploadModelInfo.value.formDataVerify(); //模型信息
        // let newtext = replaceGreaterSymbol(infoData.data.details, "@/@");
        const replacedText = infoData.data.details.replace(/>/g, "/@/");
        // this.processedText = replacedText;
        // infoData.data.details.replace(/>/g, "/@/");
        infoData.data.details = replacedText;
        console.log(infoData.data.details);
        let modelFile = infoData.isVerify ? modelUpload.value.fileVerify() : ""; //模型文件

        if (infoData.isVerify && modelFile.isVerify) {
          infoData.data.vae = modelFile.data.vaeFile.url;
          infoData.data.kind = modelFile.data.kind.url;
          infoData.data.isCommercial = infoData.data.isCommercial ? 0 : 1;
          infoData.data.isFusion = infoData.data.isFusion ? 0 : 1;
          let modelInfoFormData = {
            type: 1,
            data: modelFile.data.modelFile,
            vaeFile: modelFile.data.vaeFile,
            ...infoData.data,
          };
          data.modelPutData[0] = modelInfoFormData;
          data.stepActive = data.stepActive + 1;

          // if(data.modelPutData[1]) {
          //   proxy.$nextTick(()=>{
          //     data.backImgData = data.modelPutData[1].data;
          //     console.log(data.backImgData)
          //   })
          // }
        }
      } else if (data.stepActive == 1) {
        let imgInfoData = uploadImgInfo.value.formDataVerify(); //图片信息
        let imgFile = imgInfoData.isVerify
          ? imgUploadRef.value.fileVerify()
          : ""; //图片文件
        if (imgFile && imgFile.isVerify) {
          let newImgFile = imgFile.data.imgFile.filter((item) => item.url);
          // 提示词适用本组图片
          if (imgInfoData.isAllPrompt) {
            newImgFile.forEach((item) => {
              item.text = newImgFile.prompt;
            });
          }

          let isImgPrompt = true;
          newImgFile.forEach((item) => {
            if (!item.text) isImgPrompt = false;
            item.type = 0;
            item.prompt = item.text;
          });

          // if(!isImgPrompt) {
          //   return ElMessage.error("提示词不能为空")
          // };

          imgInfoData.data.isCommercial = imgInfoData.data.isCommercial ? 0 : 1;
          imgInfoData.data.isAllPrompt = imgInfoData.isAllPrompt ? 0 : 1;

          imgInfoData.data.sg = imgInfoData.data.sg ? 0 : 1;

          data.modelPutData[1] = {
            ...imgInfoData.data,
            data: newImgFile,
            types: data.modelPutData[0].types,
            categoryId: data.modelPutData[0].categoryId,
            source: "",
            // type:0
          };

          if (!data.agreement) {
            return ElMessage.error("请阅读并同意用户协议!");
          }

          if (imgInfoData.isVerify && imgFile.isVerify && data.agreement)
            data.stepActive = data.stepActive + 1;
        }
      }
    };

    // 发布
    let pushModel = () => {
      // 添加版本
      if (
        data.versionList.length > 1 &&
        !data.versionList[data.versionActive].id
      ) {
        addModelAddVersion();
      } else {
        data.modelPutData[0].details.replace(/[\r\n]/g, "");
        console.log(data.modelPutData[0].details.replace(/[\r\n]/g, ""));
        data.modelPutData.forEach((item) => {
          item.version = 1;
        });
        addpicture(data.modelPutData).then((res) => {
          ElMessage.success("上传成功!");
          router.push("/");
        });
      }
    };

    // 确认修改
    let updateModel = async () => {
      // console.log(data.modelPutData[1])

      await modelUpdate({ id: data.modelId, ...data.modelPutData[0] }).then(
        (res) => {
          // ElMessage.success("修改成功!");
          // data.stepActive = 0;
          // getModelOther(data.versionList[data.versionActive].id);
        }
      );

      imgUpdate({ id: data.modelId, ...data.modelPutData[1] }).then((res) => {
        ElMessage.success("修改成功!");
        data.stepActive = 0;
        getModelOther(data.versionList[data.versionActive].id);
        router.back();
      });
    };

    // 添加版本
    let addModelAddVersion = () => {
      let versionId = "";
      data.versionList.forEach((item) => {
        if (item.modelVersion === 0) {
          versionId = item.id;
        }
      });

      data.modelPutData[0].versionId = versionId;
      modelAddVersion(data.modelPutData).then((res) => {
        ElMessage.success("上传成功!");
        router.push("/");
      });
    };

    onMounted(() => {
      // 获取路由id 判断是否编辑
      let modelId = router.currentRoute.value.query.id;

      let isExamine = router.currentRoute.value.query.isExamine;
      data.isExamine = isExamine;
      if (modelId) {
        getDetail(modelId);
        data.modelId = modelId;
      } else {
        store.commit("delUpdateModelInfo");
      }
    });

    return {
      replaceGreaterSymbol,
      numToKW,
      versionClick,
      userInfo,
      pushModel,
      lastClick,
      uploadImgInfo,
      imgUploadRef,
      setActiveImgText,
      imgChange,
      modelUpload,
      nextClick,
      uploadModelInfo,
      kindChange,
      uploadSucess,
      setImgUpload,
      addVersion,
      updateModel,
      ...toRefs(data),
    };
  },
});
</script>
<style lang="scss" scoped>
.upload-model-box {
  // padding: 30px 0 60px;
  padding-bottom: 60px;
  padding-top: 30px;
  height: 100%;
}
.next-btn {
  margin-top: 20px;
  margin-right: 20px;
}

.btn {
  height: 40px;
  width: 100px;
  user-select: none;
  border-radius: 10px;
  background: linear-gradient(90deg, #9ed8e6 0%, #a1f0c0 100%);
  color: #ffffff;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  &:active {
    transform: scale(0.98);
  }
}
.btn-disabled {
  background: linear-gradient(90deg, #9ed8e6 0%, #a1f0c0 100%);
}
.agreement-checkbox {
  margin-top: 10px;
}
.agreement-link {
  font-size: 12px;
  line-height: 30px;
  height: 30px;
  margin-top: 10px;
  color: #656f79;
}

.model-info-content-box {
  margin-left: 20px;
  width: 460px;

  // 用户信息
  .user-info-box {
    .user-info {
      .user-img {
        width: 48px;
        height: 48px;
        border-radius: 50%;
      }
      .user-name-box {
        padding-left: 10px;
        .user-name {
          font-size: 14px;
          font-weight: bold;
        }
        .user-num {
          color: #656f79;
          font-size: 12px;
          padding-top: 5px;
          > div:first-child {
            margin-right: 10px;
          }
          > div {
            > img {
              width: 13px;
              margin-right: 3px;
            }
          }
        }
      }
    }
  }

  // 步骤
  .step-item {
    // padding-top: 40px;
    padding: 40px 0 30px;
    .step {
      .step-circle {
        font-size: 16px;
        color: #656f79;
        width: 30px;
        height: 30px;
        background: #f7f9fa;
        border-radius: 50%;
        // margin-right: 10px;
      }

      .step-title {
        font-size: 14px;
        color: #656f79;
        padding-left: 10px;
      }
    }
    .setp-line {
      width: 60px;
      height: 0px;
      opacity: 1;
      border: 1px solid #ececec;
      margin: 0 13px;
    }
    .step-line-active {
      border: 1px solid #64c8dc;
    }
  }
  .step-item-active {
    .step {
      .step-circle {
        background: linear-gradient(90deg, #9ed8e6 0%, #a1f0c0 100%);
        color: #ffffff;
        font-weight: bold;
      }

      .step-title {
        color: #64c8dc;
      }
    }
  }

  // 版本
  .model-version {
    padding-bottom: 20px;
    .model-version-item {
      width: 84px;
      height: 30px;
      margin-right: 10px;
      font-size: 12px;
      color: #656f79;
      background: #f7f9fa;
      border-radius: 6px;
      cursor: pointer;

      .add-cion {
        width: 16px;
        height: 16px;
        margin-right: 2px;
      }
    }
    .model-version-item-active {
      background: rgba(100, 200, 220, 0.12);
      color: #64c8dc;
    }
  }
}
</style>
